package com.m3958.firstgwt.server.dao;

import java.util.List;

import com.google.inject.Inject;
import com.m3958.firstgwt.client.types.ProtectLevel;
import com.m3958.firstgwt.client.types.ServerErrorCode;
import com.m3958.firstgwt.server.model.Asset;
import com.m3958.firstgwt.server.model.AssetFolder;
import com.m3958.firstgwt.server.service.SiteConfigService;
import com.m3958.firstgwt.server.session.SessionUser;
import com.m3958.firstgwt.server.types.SmartError;
import com.m3958.firstgwt.server.types.TreeModel;

public class AssetFolderChangeStrategy extends TreeChangeStrategy implements ModelChangeStrategy<AssetFolder> {
	
	@Inject
	SessionUser su;
	
	@Inject
	protected SiteConfigService scs;

	@Override
	public boolean extraPersistTask(AssetFolder model){
		if(model.getPerpage() == 0)model.setPerpage(getPerpageFromSite());
		if(model.getParent() != null){
			model.setProtectLevel(model.getParent().getProtectLevel());
		}else{
			if(model.getProtectLevel() == null || model.getProtectLevel().isEmpty())model.setProtectLevel(ProtectLevel.PUBLIC);
		}
		return checkDuplication(model);
	}
	
	
	private boolean checkDuplication(AssetFolder model) {
		if(model.getParent() == null){
			AssetFolderDao adao = injector.getInstance(AssetFolderDao.class);
			List<AssetFolder> ss = adao.getTopTreeNode();
			for(AssetFolder s : ss){
				if(s.getName().equals(model.getName())){
					getErrors().addError(new SmartError("同级目录不能重名！", ServerErrorCode.DUPLICATE_RECORD));
					return false;
				}
			}
		}else{
			int i=0;
			for(TreeModel<AssetFolder> s :model.getParent().getChildren()){
				if(((AssetFolder) s).getName().equals(model.getName())){
					i++;
				}
			}
			if(i>1){
				getErrors().addError(new SmartError("同级目录不能重名！", ServerErrorCode.DUPLICATE_RECORD));
				model.getParent().removeChildren(model);
				return false;
			}
		}
		return true;
		
	}
	

	@Override
	public boolean extraRemoveTask(AssetFolder model) {
		
		AssetFolder f = (AssetFolder) model;
		
		if(f.getChildren().size() > 0){
			getErrors().addError(new SmartError("请先删除子目录！", ServerErrorCode.DEPENDENCY_ERROR));
			return false;
		}
		
		for(Asset a: model.getAssets()){
			a.getFolders().remove(model);
		}
		return true;
	}
	
	
	@Override
	public boolean extraUpdateTask(AssetFolder model,AssetFolder newModel){
		return true;
	}

	@Override
	public boolean afterPersist(AssetFolder model) {
		createPerRoleAsignToUser(model);
		return false;
	}

}
